package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


    /**
     * 菜品分页查询业务逻辑
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品业务逻辑
     * @param ids
     */
    @Override
    public void deleteBath(List<Long> ids) {
        //判断当前菜品能否删除 --是否存在起售中的菜品
        ids.stream().forEach(id -> {
            if (dishMapper.getById(id).getStatus() == StatusConstant.ENABLE) {
                //不能删除 抛异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //判断当前菜品是否被套餐setmeal_dish关联--关联则不能删除
        List<Long> setmaelIds = setmealDishMapper.getSetmealIdsDishId(ids);
        if (setmaelIds != null && setmaelIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //批量删除菜品中的数据
        dishMapper.deleteByIds(ids);
        //批量删除口味数据
        //delete from dish_flavor where dish_id in (?,?,?)
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 菜品起售停售业务逻辑
     * 菜品起售表示该菜品可以对外售卖，在用户端可以点餐，菜品停售表示此菜品下架，用户端无法点餐。
     * 业务规则为：如果执行停售操作，则包含此菜品的套餐也需要停售。
     * @param status
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startOrStop(Integer status, Long id) {
        //使用 Category 类的 builder() 方法创建一个 Category 对象。 后续优化
        //这是通过 Lombok 的 @Builder 注解实现的，简化了对象的创建过程。
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        Integer status1 = dishMapper.getById(id).getStatus();
        Integer disable = StatusConstant.DISABLE;
        if (status1 == disable) {
            //套餐停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            //查询setmeal_id
            List<Long> setmealIdsDishId = setmealDishMapper.getSetmealIdsDishId(dishIds);

            if (setmealIdsDishId != null && setmealIdsDishId.size() > 0) {
                for (Long setmealId : setmealIdsDishId) {
                    //创建套餐对象，设置id,status
                    Setmeal setmeal = Setmeal.builder().id(setmealId).status(StatusConstant.DISABLE).build();
                    setmealMapper.update(setmeal);
                }
            }

        }


    }

    /**
     * 新增菜品业务逻辑
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1条数据
        dishMapper.insert(dish);

        //获取菜品的主键ID
        Long dishId = dish.getId();
        //获取口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //遍历口味
        if (flavors != null && flavors.size() > 0) {
            //插入n条
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
        }
        //批量插入口味
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 根据id查询菜品和对应的口味业务逻辑
     * @param id
     * @return
     */
    @Override
    public DishVO getDishByIdWithFlavor(Long id) {
        //查询菜品表
        Dish dish = dishMapper.getById(id);
        //查询口味表
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(id);

        //封装成dishVO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 修改菜品业务逻辑
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish); //拷贝属性

        //修改菜品
        dishMapper.update(dish);
        //当修改口味时，先删除原有的口味，再添加新的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //插入口味
            //获取口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
            //遍历口味
        if (flavors != null && flavors.size() > 0) {
            //插入n条
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
        }
        //批量插入口味
        dishFlavorMapper.insertBatch(flavors);

    }
}
